//
//  VertifyViewController.m
//  51易借
//
//  Created by 张睿 on 2017/8/17.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "VertifyViewController.h"
#import "FinishViewController.h"

@interface VertifyViewController ()

@property (nonatomic, weak)UIImageView * topView;
@property (nonatomic, weak)UIView * inputView;
@property (nonatomic, weak)UILabel * accountLabel;
@property (nonatomic, weak)UILabel * telTextField;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, weak)UILabel * veriftyLabel;
@property (nonatomic, weak)UITextField * veriftyTextField;
@property (nonatomic, weak)UIView * verticalLineView;
@property (nonatomic, weak)UIButton * resentButton;
@property (nonatomic, weak)UIButton * finishButton;
//计时器
@property (nonatomic, strong)NSTimer * countDownTimer;

@end

//倒计时总的秒数
static NSInteger  secondsCountDown = 60;

@implementation VertifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupNavBar];
    [self setupUI];
}


- (void)setupNavBar{
    
    self.title = @"验证码";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)setupUI{
    
    UIImageView * topView = [UIImageView new];
    
    topView.backgroundColor = ColorWithRGB(0xff7907);
    
    self.topView = topView;
    
    [self.view addSubview:self.topView];
    
    
    UIView * inputView = [UIView new];
    
    inputView.backgroundColor = [UIColor whiteColor];
    inputView.layer.borderColor = [ColorWithRGB(0xe6e6e6) CGColor];
    inputView.layer.borderWidth = 0.5 * SCREENH6;
    
    self.inputView = inputView;
    
    [self.view addSubview:self.inputView];
    
    
    UILabel * accountLabel = [UILabel new];
    
    accountLabel.text = @"账号";
    accountLabel.textColor = ColorWithRGB(0x303c41);
    accountLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.accountLabel = accountLabel;
    
    [self.view addSubview:self.accountLabel];
    
    
    UILabel * accountText = [[UILabel alloc] init];
    
   
    accountText.textColor = ColorWithRGB(0x303c41);
    accountText.text = self.telString;
    accountText.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13 * SCREENH6];
    
    self.telTextField = accountText;
    
    [self.view addSubview:self.telTextField];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe6e6e6);
    
    self.lineView = lineView;
    
    [self.view addSubview:self.lineView];
    
    
    UILabel * veriftyLabel = [UILabel new];
    
    veriftyLabel.text = @"验证码";
    veriftyLabel.textColor = ColorWithRGB(0x303c41);
    veriftyLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.veriftyLabel = veriftyLabel;
    
    [self.view addSubview:self.veriftyLabel];
    
    
    UITextField * veriftyTextField = [[UITextField alloc] init];
    
    veriftyTextField.borderStyle = UITextBorderStyleNone;
    veriftyTextField.backgroundColor = [UIColor clearColor];
    veriftyTextField.layer.borderColor = [[UIColor clearColor] CGColor];

    //设置光标颜色
    accountText.tintColor = ColorWithRGB(0xa5a5a5);
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xa5a5a5);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:13 * SCREENH6];
    veriftyTextField.tintColor = ColorWithRGB(0xa5a5a5);
    //修改占位符文字颜色
    veriftyTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:attrs];
    veriftyTextField.textColor = ColorWithRGB(0x303c41);
    veriftyTextField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    veriftyTextField.leftViewMode = UITextFieldViewModeAlways;
    veriftyTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13 * SCREENH6];
    veriftyTextField.keyboardType = UIKeyboardTypeNumberPad;
    
    self.veriftyTextField = veriftyTextField;
    
    [self.view addSubview:self.veriftyTextField];
    
    
    UIView * verticalLineView = [UIView new];
    
    verticalLineView.backgroundColor = ColorWithRGB(0xe6e6e6);
    
    self.verticalLineView = verticalLineView;
    
    [self.view addSubview:self.verticalLineView];
    
    
    
    UIButton * resentButton = [UIButton new];
    //300 * 42
    [resentButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [resentButton setBackgroundColor:[UIColor whiteColor]];
    [resentButton setTitleColor:ColorWithRGB(0xff7907) forState:UIControlStateNormal];
    [resentButton addTarget:self action:@selector(didGetVeriftyButton) forControlEvents:UIControlEventTouchUpInside];
    resentButton.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.resentButton = resentButton;
    
    [self.view addSubview:self.resentButton];
    
    
    UIButton * finishButton = [UIButton new];
    //300 * 42
    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
    [finishButton setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
    [finishButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [finishButton addTarget:self action:@selector(didFinishButton) forControlEvents:UIControlEventTouchUpInside];
    finishButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    self.finishButton = finishButton;
    
    [self.view addSubview:self.finishButton];
    
    
}


- (void)viewDidLayoutSubviews{
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(64 * SCREENH6);
    }];
    
    
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topView.mas_bottom).offset(10 * SCREENH6);
        make.leading.mas_equalTo(self.view).offset(5 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-5 * SCREENH6);
        make.height.mas_equalTo(106 * SCREENH6);
    }];
    
    [self.accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.inputView).offset(17 * SCREENH6);
        make.leading.mas_equalTo(self.inputView).offset(15 * SCREENH6);
    }];
    
    [self.telTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(270 * SCREENH6);
        make.centerY.mas_equalTo(self.accountLabel);
        make.trailing.mas_equalTo(self.inputView);
        make.height.mas_equalTo(45 * SCREENH6);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.inputView);
        make.height.mas_equalTo(0.5 * SCREENH6);
        make.top.mas_equalTo(self.telTextField.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.veriftyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.accountLabel);
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(17 * SCREENH6);
    }];
    
    [self.veriftyTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.height.mas_equalTo(self.telTextField);
        make.centerY.mas_equalTo(self.veriftyLabel);
        make.width.mas_equalTo(170 * SCREENH6);
    }];
    
    [self.verticalLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.veriftyTextField.mas_trailing);
        make.width.mas_equalTo(0.5 * SCREENH6);
        make.top.bottom.mas_equalTo(self.veriftyTextField);
    }];
    
    
    [self.resentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.verticalLineView.mas_trailing);
        make.trailing.mas_equalTo(self.inputView).offset(-3 * SCREENH6);
        make.top.bottom.mas_equalTo(self.veriftyTextField);
    }];
    
    [self.finishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(42 * SCREENH6);
        make.width.mas_equalTo(300 * SCREENH6);
        make.top.mas_equalTo(self.inputView.mas_bottom).offset(120 * SCREENH6);
    }];
    

}


- (void)setupDownTimer{
    
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    
    [self.resentButton setTitle:[NSString stringWithFormat:@"%lds后重新获取",(long)secondsCountDown] forState:UIControlStateDisabled];
    
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown == 0){
        
        [_countDownTimer invalidate];
        
        [self.resentButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.resentButton.enabled = YES;
    }
}

- (void)didGetVeriftyButton{
    
    [self.telTextField resignFirstResponder];
    
    
    BOOL next = [self isMobileNumber:self.telTextField.text];
    
    if (next) {
        
        self.resentButton.enabled = NO;
        secondsCountDown = 60;
        
        [self setupDownTimer];
        
        NSDictionary * parameters = @{@"userPhone":self.telTextField.text,@"smsType":@"1"};
        
        [[NetworkTool shareManager] POST:@"user/sendSmsByMobilePhone.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
            
            if ([code isEqualToString:@"0"]) {
                
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseObject[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"==%@",error);
            
        }];
        
    }else{
        
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请输入正确的手机号"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  //响应事件
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}


- (void)didFinishButton{
    
    NSString * registrationID = [[NSUserDefaults standardUserDefaults] objectForKey:@"registrationID"];
    
    NSDictionary * parameters = @{@"userPhone":self.telTextField.text,@"password":self.password,@"smsCode":self.veriftyTextField.text,@"registerId":NANilStr(registrationID)};
    
    [[NetworkTool shareManager] POST:@"user/register.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        NSString * code = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
    

            FinishViewController * finishVC = [FinishViewController new];
            
            finishVC.telString = self.telString;
            finishVC.password = self.password;
            DEF_SET_OBJECT(self.telTextField.text,@"tel");
            [self.navigationController pushViewController:finishVC animated:YES];
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"==%@",error);
        
    }];

}



//正则表达式判断手机号是否正确
- (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/149/153/180/181/189/173/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170/171
    
    NSString *MOBILE = @"^1(3[0-9]|4[579]|5[0-35-9]|8[0-9]|7[0136-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}


- (void)backToLastView{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)viewDidDisappear:(BOOL)animated{
    
    [_countDownTimer invalidate];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.telTextField resignFirstResponder];
    [self.veriftyTextField resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
